﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Web.Mvc;
using IGMVC.Web.Helpers;
using Infragistics.UltraChart.Data.Series;
using IGChart = Infragistics.WebUI.UltraWebChart;

namespace IGMVC.Web.Helpers.UltraChart
{
    public static class UltraChartExtensions
    {
        public static string Chart(this HtmlHelper html, ISeries dataSeries, string imageFolderUrl)
        {
            return Chart(html, dataSeries, null, imageFolderUrl);
        }

        public static string Chart(this HtmlHelper html, ISeries dataSeries, string presetName, string imageFolderUrl)
        {
            return Chart(html, new[] { dataSeries }, presetName, imageFolderUrl);
        }

        public static string Chart(this HtmlHelper html, IEnumerable<ISeries> dataSeries, string presetName, string imageFolderUrl)
        {
            var httpContext = html.ViewContext.HttpContext;

            var chart = new IGChart.UltraChart();

            // Load the UI presets from a preset file
            var preset = new ControlPreset(presetName);
            chart.LoadPreset(preset.GetFilePath(), true);

            // Populate with the data series that were passed in
            foreach (var series in dataSeries)
                chart.Series.Add(series);

            // Save to disk
            var imagePath = imageFolderUrl + Guid.NewGuid() + ".jpg";
            chart.SaveTo(httpContext.Server.MapPath(imagePath), ImageFormat.Jpeg);

            // Render the <img> tag pointing to the saved file
            var tagBuilder = new TagBuilder("img");
            tagBuilder.Attributes.Add("src", imagePath);
            return tagBuilder.ToString();
        }
    }
}
